# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import json
import time
from typing import List
from tortoise.expressions import Q
from hypertext import PagingResult
from common.utils.urls import UrlUtil
from common.models.users import UserModel
from common.models.agents import AgentRobotModel
from common.models.agents import AgentChatRecordsModel
from apps.admin.schemas.agent.chat import dialog_schema as schema


class ChatDialogService:

    @classmethod
    async def history(cls, params: schema.ChatHistorySearchIn) -> PagingResult[schema.ChatHistoryListVo]:
        """
        对话记录列表。

        Args:
            params (schema.ChatHistorySearchIn): 记录查询参数。

        Returns:
            PagingResult[schema.ChatHistoryListVo]: 记录分页列表Vo。

        Author:
            zero
        """
        # 查询条件
        where = AgentChatRecordsModel.build_search({
            "%like%": ["keyword@name"],
            "datetime": ["start_time|end_time@create_time"]
        }, params.__dict__)

        where.append(Q(is_delete=0))
        if params.user:
            pass
        if params.robot:
            pass

        # 查询数据
        _model = AgentChatRecordsModel.filter(*where).order_by("-id")
        _pager = await AgentChatRecordsModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size
        )

        # 角色字典
        role_dict = {"system": "System", "user": "Human", "assistant": "AI"}

        # 所属用户
        user_ids = [int(item["user_id"]) for item in _pager.lists if item["user_id"]]
        users: dict = await UserModel.queryUserDictsById(user_ids)

        # 所属智能体
        robot_ids = [int(item["robot_id"]) for item in _pager.lists if item["robot_id"]]
        robots: dict = await AgentRobotModel.queryRobotDictsById(robot_ids, field=["id", "name"])

        # 处理数据
        _lists = []
        for item in _pager.lists:
            user = users.get(item["user_id"], {})
            robot = robots.get(item["robot_id"], {})
            quotes = json.loads(item["quotes"] or "[]")
            context = json.loads(item["context"] or "[]")
            flows_usage = json.loads(item["flows_usage"] or "[]")

            # 处理上下文
            ctx_array = []
            for ctx in context:
                content = ctx["content"]
                if isinstance(ctx["content"], list):
                    annex, value = ("", "")
                    for ctx_item in ctx["content"]:
                        if ctx_item["type"] == "image_url":
                            annex += "Input an image\n"
                        elif ctx_item["type"] == "audio_url":
                            annex += "Input an audio\n"
                        elif ctx_item["type"] == "video_url":
                            annex += "Input an video\n"
                        elif ctx_item["type"] == "text":
                            value += ctx_item["text"] + "\n"
                    content = (annex + value).strip("\n")
                ctx_array.append({
                    "role": role_dict.get(ctx["role"], ctx["role"]),
                    "content": content
                })

            user = users.get(item["user_id"], {})
            if item["publish_id"]:
                user = {
                    "sn": item["publish_uid"],
                    "avatar": "static/images/default_avatar.png",
                    "nickname": "Guest"
                }

            # 对话模型
            chat_model = next((t.get("alias", "") for t in flows_usage if t.get("scene") == "chat"), "")

            # 推入列表
            _lists.append(schema.ChatHistoryListVo(
                id=item["id"],
                scene=item["scene"],
                question=item["question"],
                answer=item["answer"],
                context=ctx_array,
                quotes=quotes,
                usages=flows_usage,
                robot=robot.get("name", ""),
                chat_model=chat_model,
                use_tokens=item["use_tokens"],
                use_points=item["use_points"],
                ip=item["ip"],
                user_delete=item["user_delete"],
                task_time=item["task_time"],
                create_time=item["create_time"],
                update_time=item["update_time"],
                user={
                    "sn": user.get("sn", "").strip(),
                    "nickname": user.get("nickname", ""),
                    "mobile": user.get("mobile", ""),
                    "avatar": await UrlUtil.to_absolute_url(user.get("avatar", ""))
                }
            ))

        _pager.lists = _lists
        return _pager

    @classmethod
    async def delete(cls, ids: List[int]):
        """
        对话记录删除

        Args:
            ids (List[int]): ID

        Author:
            zero
        """
        await AgentChatRecordsModel.filter(id__in=ids).update(
            is_delete=1,
            delete_time=int(time.time())
        )
